import 'dart:async';

import 'package:flutter/material.dart';

class StreamDemo extends StatefulWidget {
  StreamDemo({Key key}) : super(key: key);

  _StreamDemoState createState() => _StreamDemoState();
}

class _StreamDemoState extends State<StreamDemo> {
  StreamSubscription _streamSubscription;
  StreamController _streamController;
  StreamSink _streamSink;
  // String _data = '...';
  @override
  void initState() {
    super.initState();
    print('create a Stream');
    _streamController = StreamController.broadcast();
    _streamSink = _streamController.sink;
    print('listen the Stream');
    // 给stream 添加一个订阅
    _streamSubscription = _streamController.stream
        .listen(onData, onDone: onDone, onError: onError);
    print('init the Stream over');
  }

  @override
  void dispose() {
    super.dispose();
    _streamController.close();
  }

  fetchData() async {
    await Future.delayed(Duration(seconds: 5));
    // throw 'some error happened'; //触发onError
    return 'hello ~'; //触发onData
  }

  void onData(data) {
    print('$data');
  }

  void onDone() {
    print('done');
  }

  void onError(error) {
    print('Error $error');
  }

  void _pauseStream() {
    print('pause Stream');
    _streamSubscription.pause();
  }

  void _resumeStream() {
    print('resume Stream');
    _streamSubscription.resume();
  }

  void _cancelStream() {
    print('cancel Stream');
    _streamSubscription.cancel();
  }

  _addStream() async {
    print('_add data to Stream');
    var data = await fetchData();
    // _streamController.add(data);
    _streamSink.add(data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('StreamDemo'),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            // Container(
            //   child: Text('$_data'),
            // ),
            StreamBuilder(
              stream: _streamController.stream,
              initialData: '...',
              builder: (context, snapshot) {
                return Text('${snapshot.data}');
              },
            ),

            Container(
              child: Row(
                children: <Widget>[
                  FlatButton(
                    child: Text('Add'),
                    onPressed: _addStream,
                  ),
                  FlatButton(
                    child: Text('Pause'),
                    onPressed: _pauseStream,
                  ),
                  FlatButton(
                    child: Text('Resume'),
                    onPressed: _resumeStream,
                  ),
                  FlatButton(
                    child: Text('Cancel'),
                    onPressed: _cancelStream,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
